<?php

namespace app\hotel\controller;

use think\Controller;
use app\common\library\Email;

class Business extends Controller
{
  // 继承底层构造函数
  public function __construct()
  {
    parent::__construct();

    $this->BusinessModel = model('Business.Business');
    $this->RecordModel = model('Business.Record');
    $this->PayModel = model('pay.Pay');
  }

  // 用户注册
  public function register()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收参数
      $mobile = $this->request->param('mobile', '', 'trim');
      $password = $this->request->param('password', '', 'trim');

      if (empty($password)) {
        $this->error('密码不能为空');
        exit;
      }

      //生成一个密码盐
      $salt = randstr();

      //加密密码
      $password = md5($password . $salt);

      //组装数据
      $data = [
        'mobile' => $mobile,
        'nickname' => $mobile,
        'password' => $password,
        'salt' => $salt,
        'gender' => '0', //性别
        'deal' => '0', //成交状态
        'money' => '0', //余额
        'auth' => '0', //实名认证
      ];

      //查询出云课堂的渠道来源的ID信息 数据库查询
      $data['sourceid'] = model('common/Business/Source')->where(['name' => ['LIKE', "%家居商城%"]])->value('id');

      //执行插入 返回自增的条数
      $result = $this->BusinessModel->validate('common/Business/Business')->save($data);

      if ($result === FALSE) {
        //失败
        $this->error($this->BusinessModel->getError());
        exit;
      } else {
        //注册
        $this->success('注册成功', '/user/login');
        exit;
      }
    }
  }


  // 用户登录
  public function login()
  {
    //判断是否是Post请求
    if ($this->request->isPost()) {
      //获取数据
      $mobile = $this->request->param('mobile', '', 'trim');
      $password = $this->request->param('password', '', 'trim');

      //根据手机号来查询数据存不存在
      $business = $this->BusinessModel->where(['mobile' => $mobile])->find();

      // 用户不存在
      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      //数据打印
      // var_dump($business->toArray());
      // exit;

      //验证密码
      $salt = $business['salt'];
      $password = md5($password . $salt);

      if ($password != $business['password']) {
        $this->error('密码不正确');
        exit;
      } else {
        // 删除密码和密码盐，为了防止数据展示在cookie页面中
        unset($business['password']);
        unset($business['salt']);

        //跳转会员中心，将新的数据带给前台
        $this->success('登录成功', '/user/index', $business);
        exit;
      }
    }
  }

  // 检验登录
  public function check()
  {
    // 判断是否有post请求
    $id = $this->request->param('id', '0', 'trim');
    $mobile = $this->request->param('mobile', '', 'trim');

    //查询
    $business = $this->BusinessModel->where(['id' => $id, 'mobile' => $mobile])->find();

    if ($business) {
      // 删除密码和密码盐，为了防止数据展示在cookie页面中
      unset($business['password']);
      unset($business['salt']);

      // 将新的数据带给前台
      $this->success("用户验证成功", null, $business);
      exit;
    } else {
      $this->error('用户不存在');
      exit;
    }
  }

  // 基本资料
  public function profile()
  {
    // 1.判断是否有接收到post请求
    if ($this->request->isPost()) {
      $id = $this->request->param('id', '', 'trim');
      // 接收到页面传来的数据
      $nickname = $this->request->param('nickname', '', 'trim');
      $mobile = $this->request->param('mobile', '', 'trim');
      $email = $this->request->param('email', '', 'trim');
      $gender = $this->request->param('gender', '0', 'trim');
      $code = $this->request->param('code', '', 'trim');
      $password = $this->request->param('password', '', 'trim');

      // 判断用户是否存在
      $business = $this->BusinessModel->find($id);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      // 2.组装数据，特殊的数据放在外面处理
      $data = [
        'id' => $business['id'],
        'nickname' => $nickname,
        'mobile' => $mobile,
        'gender' => $gender
      ];

      // 判断密码是否为空， 如果不为空就是修改了密码
      if (!empty($password)) {
        // 重新生成一份密码盐
        $salt = randstr();
        // 将新的密码和密码盐加密
        $password = md5($password . $salt);
        // 组装数据
        $data['salt'] = $salt;
        $data['password'] = $password;
      }

      // 判断是否修改了邮箱，判断输入的邮箱不等于数据库存入的邮箱 说明修改了邮箱
      if ($email != $business['email']) {
        // 组装数据
        $data['email'] = $email;
        $data['auth'] = '0';
      }

      // 判断是否有地区数据
      if (!empty($code)) {
        // 查询省、市、区的地区码出来
        $parentpath = model('Region')->where(['code' => $code])->value('parentpath');

        // 判断地区码是否为空 并组装省、市、区的每一个地区码
        if (!empty($parentpath)) {
          // 将字符串转换为数组
          $arr = explode(',', $parentpath);

          // 组装
          $data['province'] = isset($arr[0]) ? $arr[0] : null;
          $data['city'] = isset($arr[1]) ? $arr[1] : null;
          $data['district'] = isset($arr[2]) ? $arr[2] : null;
        }
      }

      // 判断是否有图片上传，以及错误为0
      if (isset($_FILES['avatar']) && $_FILES['avatar']['error'] == 0) {
        // 接收上传的图片
        $success = build_upload('avatar');

        // 判断删除失败结果
        if (!$success['result']) {
          // 提醒
          $this->error($success['msg']);
          exit;
        }

        // 上传成功组装数据
        $data['avatar'] = $success['data'];
      }

      // 拿到所有数据后，进行更新用户表数据
      // 这里使用到了验证器场景，区别开注册和登录后的验证信息
      $result = $this->BusinessModel->validate('common/Business/Business.profile')->isUpdate(true)->save($data);

      // 判断如果更新失败
      if ($result === FALSE) {
        // 提示
        $this->error($this->BusinessModel->getError());
        exit;
      }

      // 判断一下是否有旧图片，如果有就删除
      if (isset($data['avatar'])) {
        is_file('.' . $business['avatar']) && @unlink('.' . $business['avatar']);
      }

      $result = $this->BusinessModel->find($id);

      // 删除密码和密码盐，为了防止数据展示在cookie页面中
      unset($business['password']);
      unset($business['salt']);

      // 提示更新资料成功
      $this->success('恭喜您~更新资料成功！！', null, $result);
    }
  }

  // 用户邮箱验证
  public function email()
  {

    //加载模型
    $EmsModel = model('common/Ems');

    // 判断是否有接收到ajax请求
    if ($this->request->isPost()) {
      // 拿到action
      $action = $this->request->param('action', '', 'trim');

      //接收用户id
      $id = $this->request->param('id', 0, 'trim');

      $business = $this->BusinessModel->find($id);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      // 获取用户信息
      $email = isset($business['email']) ? $business['email'] : '';

      // 判断邮箱是否为空
      if (empty($email)) {
        // 提醒
        $this->error("邮箱地址为空");
        exit;
      }

      // action拿到
      if ($action == 'send') {

        // 如果邮箱不为空
        // 生成一个随机5位验证码
        $code = randstr(5);

        // 开启事务（撤销回滚操作）
        $EmsModel->startTrans();

        // 删掉之前的旧的验证码
        $EmsModel->where(['email' => $email])->delete();

        // 把验证码插入到数据库的pre_ems表中
        // 组装数据
        $data = [
          'event' => 'auth',
          'email' => $email,
          'code' => $code,
          'times' => 0,
        ];

        // 插入数据
        $ems = $EmsModel->save($data);

        // 如果插入失败
        if ($ems === FALSE) {
          // 提示
          $this->error('邮件插入失败');
          exit;
        }

        // 插入成功

        $name = config('site.name');
        // 设置主题
        $subject = "【{$name}】邮箱验证";

        //组装文字信息
        $message = "<div>感谢您的使用，您的邮箱验证码为：<b>$code</b></div>";

        //实例化邮箱验证类
        $PhpMailer = new Email;

        //邮箱发送有规律，不可以发送关键词
        $result = $PhpMailer
          ->to($email)
          ->subject($subject)
          ->message($message)
          ->send();

        // 检测邮箱是否发送成功
        if ($result) {
          //发送验证码成功
          //将事务提交，提交的意思就是让刚刚插入的记录真实存在到数据表中
          $EmsModel->commit();
          $this->success('邮件发送成功，请注意查收');
          exit;
        } else {
          //将刚才插入成功的验证码记录要撤销回滚
          $EmsModel->rollback();
          $this->error($PhpMailer->getError());
        }
      } else {
        // 获取输入的验证码
        $code = $this->request->param('code', '', 'trim');

        // 判断是否为空
        if (empty($code)) {
          // 提示
          $this->error('验证码不能为空');
          exit;
        }

        // 开启事务
        $EmsModel->startTrans();
        $this->BusinessModel->startTrans();

        // 查询验证码是否在数据库中存在，就是是否等于数据库中的验证码
        $where = ['email' => $email, 'code' => $code];
        $check = $EmsModel->where($where)->find();

        // 如果没有找到记录
        if (!$check) {
          // 提示
          $this->error("您输入的验证码有误！请重新输入~~");
          exit;
        }

        // 1.更新用户表，2.删除验证码记录

        // 组装数据
        $data = [
          'id' => $business['id'],
          'auth' => '1'
        ];

        // 1.执行更新用户表
        $BusinessStatus = $this->BusinessModel->isUpdate(true)->save($data);

        // 如果更新用户表失败
        if ($BusinessStatus === FALSE) {
          $this->error('用户邮箱认证失败');
          exit;
        }

        // 2.删除验证码记录
        $EmsStatus = $EmsModel->where($where)->delete();

        // 如果删除验证码记录失败，要进行回滚
        if ($EmsStatus === FALSE) {
          //先要将用户表的更新进行回滚
          $this->BusinessModel->rollback();
          $this->error('验证码记录删除失败');
          exit;
        }

        // 如果两个中的其中一个没有成功，则验证也是失败的
        if ($BusinessStatus === FALSE || $EmsStatus === FALSE) {
          $EmsModel->rollback();
          $this->BusinessModel->rollback();
          $this->error('验证失败');
          exit;
        } else {
          //提交事务
          $this->BusinessModel->commit();
          $EmsModel->commit();
          $this->success('邮箱验证成功');
          exit;
        }
      }
    }
  }

  // 用户消费记录
  public function record()
  {
    // 判断是否有post请求
    if ($this->request->isPost()) {
      // 接收用户id参数
      $busid = $this->request->param('busid', 0, 'trim');

      $this->business = $this->BusinessModel->find($busid);

      if (!$this->business) {
        $this->error('用户不存在');
        exit;
      }

      // 查询消费记录表
      $result = $this->RecordModel->where(['busid' => $busid])->order('createtime', 'desc')->select();

      if ($result) {
        $this->success('返回消费记录数据', null, $result);
        exit;
      } else {
        $this->error('返回消费记录数据失败');
        exit;
      }
    }
  }

  // 充值
  public function pay()
  {
    if ($this->request->isPost()) {
      $busid = $this->request->param('busid', 0, 'trim');
      $money = $this->request->param('money', 1, 'trim');
      $type = $this->request->param('type', 'wx', 'trim');


      //判断用户是否存在
      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      if ($money <= 0) {
        $this->error('充值金额不能小于0元');
        exit;
      }


      //发送一个接口请求出去
      $host = config('site.cdnurl');
      $host = trim($host, '/');

      //完整的请求接口地址
      $api = $host . "/pay/index/create";

      //订单支付完成后跳转的界面
      $reurl = "http://vue-shop.xdlayman.cn/#/user/pay";

      $callbackurl = $host . "/shop/user/callback";

      //携带一个自定义的参数过去 转换为json类型
      $third = json_encode(['busid' => $busid]);

      //微信收款码
      $wxcode = config('site.wxcode');
      $wxcode = $host . $wxcode;

      //支付宝收款码
      $zfbcode = config('site.zfbcode');
      $zfbcode = $host . $zfbcode;

      //充值信息
      $PayData = [
        'name' => '余额充值',
        'third' => $third,
        'originalprice' => $money,
        //微信支付
        // 'paytype' => 0,
        // 'paypage' => 1,
        //支付宝支付
        // 'paytype' => 1,
        // 'paypage' => 2,
        'paypage' => 0,
        'wxcode' => $wxcode,
        'zfbcode' => $zfbcode,
        'reurl' => $reurl,
        'callbackurl' => $callbackurl,
      ];

      //要看是哪一种支付方式
      if ($type == 'wx') {
        //微信
        $PayData['paytype'] = 0;
      } else {
        //支付宝
        $PayData['paytype'] = 1;
      }

      //发起请求
      $result = httpRequest($api, $PayData);

      //有错误
      if (isset($result['code']) && $result['code'] == 0) {
        $this->error($result['msg']);
        exit;
      }

      //将json转换为php数组
      $result = json_decode($result, true);

      $this->success('生成付款码', null, $result['data']);
      exit;
    }
  }

  //查询订单是否成功
  public function query()
  {
    if ($this->request->isPost()) {
      $busid = $this->request->param('busid', 0, 'trim');
      $payid = $this->request->param('payid', '', 'trim');

      //判断用户是否存在
      $business = $this->BusinessModel->find($busid);

      if (!$business) {
        $this->error('用户不存在');
        exit;
      }

      if (empty($payid)) {
        $this->error('支付记录不存在');
        exit;
      }

      //发送一个接口请求出去
      $host = config('site.cdnurl');
      $host = trim($host, '/');

      //完整的请求接口地址
      $api = $host . "/pay/index/status";

      //发起请求
      $result = httpRequest($api, ['payid' => $payid]);

      //将json转换为php数组
      $result = json_decode($result, true);

      if (isset($result['code']) && $result['code'] == 0) {
        $this->error($result['msg']);
        exit;
      } else {
        $status = isset($result['data']['status']) ? $result['data']['status'] : 0;
        $this->success('查询充值状态', null, ['status' => $status]);
        exit;
      }
    }
  }

  //充值回调
  public function callback()
  {
    // 判断是否有post请求过来
    if ($this->request->isPost()) {
      // 获取到所有的数据
      $params = $this->request->param();

      // 充值的金额
      $price = isset($params['price']) ? $params['price'] : 0;
      $price = floatval($price);

      // 第三方参数(可多参数)
      $third = isset($params['third']) ? $params['third'] : '';

      // json字符串转换数组
      $third = json_decode($third, true);

      // 从数组获取充值的用户id
      $busid = isset($third['busid']) ? $third['busid'] : 0;

      // 支付方式
      $paytype = isset($params['paytype']) ? $params['paytype'] : 0;

      // 支付订单id
      $payid = isset($params['id']) ? $params['id'] : 0;

      $pay = $this->PayModel->find($payid);

      if (!$pay) {
        return json(['code' => 0, 'msg' => '支付订单不存在', 'data' => null]);
      }

      $payment = '';

      switch ($paytype) {
        case 0:
          $payment = '微信支付';
          break;
        case 1:
          $payment = '支付宝支付';
          break;
      }

      //判断充值金额
      if ($price <= 0) {
        return json(['code' => 0, 'msg' => '充值金额为0', 'data' => null]);
      }

      // 加载模型
      $BusinessModel = model('Business.Business');
      $RecordModel = model('Business.Record');

      $business = $BusinessModel->find($busid);

      if (!$business) {
        return json(['code' => 0, 'msg' => '充值用户不存在', 'data' => null]);
      }

      // 开启事务
      $BusinessModel->startTrans();
      $RecordModel->startTrans();

      // 转成浮点类型
      $money = floatval($business['money']);

      // 余额 + 充值的金额
      $updateMoney = bcadd($money, $price, 2);

      // 封装用户更新的数据
      $BusinessData = [
        'id' => $business['id'],
        'money' => $updateMoney
      ];

      // 自定义验证器
      $validate = [
        [
          'money' => ['number', '>=:0'],
        ],
        [
          'money.number' => '余额必须是数字类型',
          'money.>=' => '余额必须大于等于0元'
        ]
      ];

      $BusinessStatus = $BusinessModel->validate(...$validate)->isUpdate(true)->save($BusinessData);

      if ($BusinessStatus === false) {
        return json(['code' => 0, 'msg' => $BusinessModel->getError(), 'data' => null]);
      }

      // 封装插入消费记录的数据
      $RecordData = [
        'total' => $price,
        'content' => "{$payment}充值了 $price 元",
        'busid' => $business['id']
      ];

      // 插入
      $RecordStatus = $RecordModel->validate('common/Business/Record')->save($RecordData);

      if ($RecordStatus === false) {
        $BusinessModel->rollback();
        return json(['code' => 0, 'msg' => $RecordModel->getError(), 'data' => null]);
      }

      if ($BusinessStatus === false || $RecordStatus === false) {
        $BusinessModel->rollback();
        $RecordModel->rollback();
        return json(['code' => 0, 'msg' => '充值失败', 'data' => null]);
      } else {
        $BusinessModel->commit();
        $RecordModel->commit();

        // 订单号：\r\n
        // 金额:50元
        // 支付方式：
        // 时间，
        return json(['code' => 1, 'msg' => '充值成功', 'data' => null]);
      }
    }
  }
}
